'''
Created on Apr 21, 2014

@author: sergio
'''

import psycopg2
import neodb
import neo.core
import neodb.dbutils
from quantities import Hz, mV
import numpy

class AnalogSignalDB(neo.core.AnalogSignal):
    '''
    classdocs
    '''
    def __init__(self, id_segment = None, signal = None, t_start = None,
                       sampling_rate = None, channel_index = None, name = None,
                       description = None, file_origin = None, units = None,
                       index = None):
        '''
        Constructor
        '''
        if signal == None:
            signal = []
        if sampling_rate == None:
            sampling_rate = 14400
        if units == None:
            units = mV
        
        self.signal = signal
        self.sampling_rate=sampling_rate*Hz
        self.units=units
        self.t_start = t_start,
        self.channel_index = channel_index
        self.name = name
        self.description = description
        self.file_origin = file_origin
        self.index = index
        
        self.id_segment = id_segment
        
    def save(self, connection):
        # Check mandatory values
        if self.id_segment == None:
            raise StandardError("Analogsignal must have id_segment.")
        
        if self.signal == []:
            raise StandardError("Analogsignal must have a signal.")
        
        # Format signal
        signalb = numpy.int16(self.signal)
        
        # QUERY
        cursor = connection.cursor()
        
        query = """INSERT INTO analogsignal 
                   (id_segment, signal, sampling_rate, unit, t_start, channel_index, name, description, file_origin, index)
                   VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
        unit = str(self.units).split(' ')[1]
        cursor.execute(query,[self.id_segment, psycopg2.Binary(signalb),
                              int(self.sampling_rate), unit,
                              int(self.t_start[0]), self.channel_index,
                              self.name, self.description, self.file_origin,
                              self.index])
        
        connection.commit()
        
        # Get ID
        [(id, _)] = neodb.get_id(connection, 'analogsignal', 
                                 name = self.name, 
                                 channel_index = self.channel_index, 
                                 id_segment = self.id_segment)
        
        return id

if __name__ == '__main__':
    username = 'postgres'
    password = 'postgres'
    host = '192.168.2.2'
    dbname = 'demo'
    url = 'postgresql://%s:%s@%s/%s'%(username, password, host, dbname)
    
    dbconn = psycopg2.connect('dbname=%s user=%s password=%s host=%s'%(dbname, username, password, host))
    #a = AnalogSignalDB(id_segment = 2, signal = [2,2,4,3], units = 'mV', sampling_rate=14400*Hz, t_start = 0)
    #a.save(dbconn)
    
    
    cursor = dbconn.cursor()
    cursor.execute('select signal from analogsignal')
    v = cursor.fetchall()
    v=v[0]
    v=v[0]
    numpy.frombuffer(v, numpy.int16)
    pass